package com.kcsj.service;

import java.sql.SQLException;
import java.util.List;

import com.kcsj.dao.UserDao;
import com.kcsj.model.Page;
import com.kcsj.model.User;

public class UserService {
	private UserDao uDao = new UserDao();
	
	public int register(User user) {
		int s=0;
		String t1="^[0-9]{12}$";//学号要求为12位数字
		String t2="^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$";//密码要求为字母和数字的组合（8到16位）
		try {
			if (uDao.isUsernameExist(user.getUsername())) {
				s=1;
				System.out.println(s);
				return s;
			}
			if (uDao.isEmailExist(user.getEmail())) {
				s=2;
				System.out.println(s);
				return s;
			}
			if(!user.getUsername().matches(t1)) {
				s=3;
				System.out.println(s);
				return s;
			}
			if(!user.getPassword().matches(t2)) {
				s=4;
				System.out.println(s);
				return s;
			}
			System.out.println(s);
			uDao.addUser(user);
			return s;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		s=5;
		return s;//失败
	}

	public User login(String ue, String password) {
		User user = null;
		try {
			user = uDao.selectByUsernamePassword(ue, password);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (user != null) {
			return user;
		}
		try {
			user = uDao.selectByEmailPassword(ue, password);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (user != null) {
			return user;
		}
		return null;
	}

	public User selectById(int id) {
		User u = null;
		try {
			u = uDao.selectById(id);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return u;
	}

	public void updateUserAddress(User user) {
		try {
			uDao.updateUserAddress(user);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void updatePwd(User user) {
		try {
			uDao.updatePwd(user);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public Page getUserPage(int pageNo) {
		Page p = new Page();
		p.setPageNo(pageNo);
		int pageSize = 7;
		int totalCount = 0;
		try {
			totalCount = uDao.selectUserCount();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		p.setPageSizeAndTotalCount(pageSize, totalCount);
		List list = null;
		try {
			list = uDao.selectUserList(pageNo, pageSize);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		p.setList(list);
		return p;
	}

	public boolean delete(int id) {
		try {
			uDao.delete(id);
			return true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}

}
